/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.academy.model.Body;
import ar.uba.fi.posgrado.common.dao.CustomerDAO;
import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.MissingArgumentException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;
import ar.uba.fi.posgrado.common.util.CriterionBuilder;
import ar.uba.fi.posgrado.common.util.ExpressionOperator;
import ar.uba.fi.posgrado.economy.exception.PosgradoRuleException;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.CustomerAccount;
import ar.uba.fi.posgrado.economy.model.Debt;
import ar.uba.fi.posgrado.economy.service.CustomerAccountService;
import ar.uba.fi.posgrado.economy.service.CustomerService;
import ar.uba.fi.posgrado.economy.service.DebtService;

/**
 * Implementacion de {@link CustomerService customer service}
 * 
 * @author pablo.tortorella
 * 
 */
public class CustomerServiceImpl implements CustomerService {

	/** Logger */
	private static Logger logger = Logger.getLogger(CustomerServiceImpl.class);

	private CustomerDAO customerDAO;

	private CustomerAccountService customerAccountService;

	private DebtService debtService;

	/**
	 * @return the customerAccountService
	 */
	public CustomerAccountService getCustomerAccountService() {
		return customerAccountService;
	}

	/**
	 * @param customerAccountService
	 *            the customerAccountService to set
	 */
	public void setCustomerAccountService(
			CustomerAccountService customerAccountService) {
		this.customerAccountService = customerAccountService;
	}

	/**
	 * @param debtService
	 *            the debtService to set
	 */
	public void setDebtService(DebtService debtService) {
		this.debtService = debtService;
	}

	/**
	 * @return the customerDAO
	 */
	public CustomerDAO getCustomerDAO() {
		return customerDAO;
	}

	/**
	 * @param customerDAO
	 *            the customerDAO to set
	 */
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	public CustomerServiceImpl() {

	}

	/**
	 * Consturctor para prueba unitaria
	 * 
	 * @param customerDAO
	 */
	public CustomerServiceImpl(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	/**
	 * @see ar.uba.fi.posgrado.economy.service.CustomerService#delete(ar.uba.fi.posgrado.common.model.Customer)
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(Customer customer) throws PosgradoRuntimeException,
			PosgradoException {
		try {
			Debt debt = new Debt();
			debt.setCustomer(customer);
			List<Debt> lista = debtService.getDebtsByConditions(debt);
			if (lista.size() > 0) {
				String message = "Este cliente tiene deudas asociadas y ya no puede borrarse del sistema.";
				logger.info(message);
				throw new PosgradoRuleException(message);
			}

			this.getCustomerDAO().remove(customer);
			logger.info("Cliente: " + customer + ", eliminado con exito");
		} catch (ConstraintViolationException e) {
			StringBuffer mensaje = new StringBuffer(
					"El cliente con razon social ");
			mensaje.append(customer.getCorporateName());
			mensaje.append(" es responsable de pago de uno o ");
			mensaje.append("más alumnos del sistema. No puede ser borrado.");
			throw new RepeatedNameException(mensaje.toString());
		} catch (DAOException e) {
			throw new PosgradoException("Error al borrar el cliente: "
					+ customer, e);
		}
	}

	/**
	 * @see ar.uba.fi.posgrado.economy.service.CustomerService#getAll()
	 */
	@Transactional(readOnly = true)
	public List<Customer> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		try {
			List<Customer> response = this.getCustomerDAO().findAll();
			logger.info("Clientes encontrados: " + response.size());
			return response;
		} catch (DAOException e) {
			throw new PosgradoException("Excepcion buscando clientes", e);
		}
	}

	/**
	 * @see ar.uba.fi.posgrado.economy.service.CustomerService#getById(Long id)
	 */
	@Transactional(readOnly = true)
	public Customer getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		try {
			Customer response = (Customer) this.getCustomerDAO().findById(id);
			logger.info("Cliente con Id: " + id + ", encontrado con exito");
			return response;
		} catch (DAOException e) {
			throw new PosgradoException(
					"Excepcion buscando el Cliente con Id: " + id, e);
		}
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(Customer customer) throws PosgradoRuntimeException,
			PosgradoException {
		if (StringUtils.isBlank(customer.getName())
				|| StringUtils.isBlank(customer.getCorporateName())) {
			if (logger.isDebugEnabled()) {
				logger.debug("El Nombre y la Razon Social "
						+ "son datos obligatorios al dar de alta un Cliente");
			}
			throw new MissingArgumentException(
					"El Nombre y la Razon Social son datos obligatorios "
							+ "al dar de alta un Cliente");
		}
		try {
			/*
			 * Analiza si no existe un cliente con la misma razon social. En ese
			 * caso arroja una RepeatedInstanceException
			 */
			this.getCustomerDAO().findByCorporateName(
					customer.getCorporateName());
			StringBuffer mensaje = new StringBuffer(
					"El cliente con razon social ");
			mensaje.append(customer.getCorporateName());
			mensaje.append(" no es valido.");
			mensaje.append(" Ya existe un cliente con esa razon social.");
			throw new RepeatedNameException(mensaje.toString());
		} catch (NoSuchEntityException e) {
			// Si entro aca es xq no existia, lo cual esta bien. Sigue abajo
		}
		try {
			customer.setRegisterDate(new Date()); // HOY!
			CustomerAccount account = newAccountFromCustomer(customer);
			// crea la cuenta corriente asociada
			this.customerAccountService.create(account);
			customer.setAccount(account);
			// crea el cliente en la base de datos
			this.getCustomerDAO().save(customer);

			if (logger.isInfoEnabled()) {
				logger.info("Cliente: " + customer + " creado con exito");
			}
		} catch (DAOException e) {
			throw new PosgradoException("Excepcion al crear el cliente: "
					+ customer, e);
		}
	}

	public CustomerAccount newAccountFromCustomer(Customer customer) {
		CustomerAccount account = new CustomerAccount();
		account.setCustomer(customer);
		account.setInFavorCredit(0d);
		account.setTotalDebt(0d);
		return account;
	}

	public Customer getByCorporateName(String corporateName)
			throws PosgradoRuntimeException, PosgradoException {
		Customer response = null;
		response = this.getCustomerDAO().findByCorporateName(corporateName);
		if (logger.isInfoEnabled()) {
			logger.info("Un Cliente encontrado con razon social: "
					+ corporateName);
		}
		return response;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public Customer update(Customer customer) throws PosgradoRuntimeException,
			PosgradoException, NoSuchEntityException, RepeatedNameException {

		Customer toUpdateCustomer = this.getById(customer.getId());

		// hay que buscar el cliente, cambiarlo y volver a persistirlo
		if ((StringUtils.isBlank(customer.getName()) || (StringUtils
				.isBlank(customer.getCorporateName())))) {
			StringBuffer mensaje = new StringBuffer(
					"El Nombre y la Razon Social son datos obligatorios para dar de alta un Cliente");
			MissingArgumentException e = new MissingArgumentException(mensaje
					.toString());
			if (logger.isDebugEnabled()) {
				logger.debug(mensaje, e);
			}
			throw e;
		}

		try {
			Customer c = this.getByCorporateName(customer.getCorporateName());
			if (c.getId() != toUpdateCustomer.getId()) {
				StringBuffer mensaje = new StringBuffer(
						"No se puede actualizar el cliente. Ya hay otro cliente en el sistema con la razon social ");
				mensaje.append(customer.getCorporateName());
				throw new RepeatedNameException(mensaje.toString());
			} else {
				toUpdateCustomer.setName(customer.getName());
				toUpdateCustomer.setCorporateName(customer.getCorporateName());
				toUpdateCustomer.setAddress(customer.getAddress());
				toUpdateCustomer.setTerms(customer.getTerms());
				toUpdateCustomer.setPhone(customer.getPhone());
				toUpdateCustomer.setMobile(customer.getMobile());
				toUpdateCustomer.setEmail(customer.getEmail());
				toUpdateCustomer.setContact(customer.getContact());
				toUpdateCustomer.setDocument(customer.getDocument());

				this.getCustomerDAO().update(toUpdateCustomer);
				customer = toUpdateCustomer;
			}
		} catch (NoSuchEntityException e) {
			// significa que esta todo bien y puede actualizar el alumno
			toUpdateCustomer.setName(customer.getName());
			toUpdateCustomer.setCorporateName(customer.getCorporateName());
			toUpdateCustomer.setAddress(customer.getAddress());
			toUpdateCustomer.setTerms(customer.getTerms());
			toUpdateCustomer.setPhone(customer.getPhone());
			toUpdateCustomer.setMobile(customer.getMobile());
			toUpdateCustomer.setEmail(customer.getEmail());
			toUpdateCustomer.setContact(customer.getContact());
			toUpdateCustomer.setDocument(customer.getDocument());

			this.getCustomerDAO().update(toUpdateCustomer);
			customer = toUpdateCustomer;
		}

		return customer;
	}

	/**
	 * @see ar.uba.fi.posgrado.economy.service.CustomerService#getByMatchingCorporateName(java.lang.String)
	 */
	@Transactional(readOnly = true)
	public List<Customer> getByMatchingCorporateName(String corporateName)
			throws PosgradoRuntimeException, PosgradoException {
		List<Customer> response = null;
		try {
			CriterionBuilder builder = new CriterionBuilder();
			builder.add("corporateName", corporateName,
					ExpressionOperator.ILike);
			response = this.getCustomerDAO().findByCriterions(
					builder.toCriterions());

			if (logger.isDebugEnabled()) {
				logger.debug("# Clientes con razon social " + corporateName
						+ " = " + response.size());
			}
		} catch (DAOException e) {
			throw new PosgradoException(
					"Excepcion buscando clientes con criterios", e);
		}

		return response;
	}

	/**
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List,
	 *      ar.uba.fi.posgrado.common.model.User)
	 */
	public List<Customer> filter(List<Customer> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		if (!user.hasBodyRole()) {
			return list;
		}
		final Body body = user.getBody();
		if (logger.isDebugEnabled()) {
			logger
					.debug("El usuario tiene el rol Ente. Filtrando clientes para el "
							+ "ente: " + body);
		}
		/*
		 * Si hay alguna deuda (una o mas) del ente en cuestion entonces es xq
		 * se puede devolver.
		 */
		final Debt debt = new Debt();
		debt.setBody(body);

		final DebtService debtServiceAux = this.debtService;

		CollectionUtils.filter(list, new Predicate() {
			public boolean evaluate(Object object) {
				Customer customer = (Customer) object;
				// Cliente a la condicion de busqueda
				debt.setCustomer(customer);

				try {
					List<Debt> debts = debtServiceAux
							.getDebtsByConditions(debt);
					// Si hay algo entonces es xq las deudas pertenecen al curso
					if (debts.size() >= 1) {
						return true;
					}
				} catch (PosgradoException e) {
					// No deberia tirar esta exception, pero en ese caso no se
					// descarta...
					return true;
				}
				return false;
			}
		});

		return list;
	}

}
